package com.thiswhyme.demo.msgpush.core.impl.websocket.event;

import com.thiswhyme.demo.msgpush.core.event.AbstractPushEventWsHandler;
import com.thiswhyme.demo.msgpush.core.event.bean.WebSocketEvent;
import com.thiswhyme.demo.msgpush.core.impl.websocket.SessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * @description: WebSocket消息推送事件处理器-ws实现
 * @author: thiswhyme
 * @date: 2021/9/28
 */
@Slf4j
public class PushEventWsHandler extends AbstractPushEventWsHandler {

    @Override
    public void doHandle(WebSocketEvent event) {
        event.getIdentifiers().forEach(identifier -> {
            WebSocketSession session = SessionManager.get(identifier);
            if (null != session) {
                try {
                    if (session.isOpen()) {
                        session.sendMessage(new TextMessage(event.getMsgContent()));
                        log.debug("【{}】完成推送", identifier);
                    } else {
                        log.error("【{}】推送失败，Session已关闭", identifier);
                    }
                } catch (IOException e) {
                    log.error("【{}】推送失败", identifier, e);
                }
            } else {
                log.debug("【{}】Session已关闭或不在该实例上，跳过推送", identifier);
            }
        });
    }
}
